package com.zhu.rpc.client;


import com.zhu.rpc.MsgType;
import com.zhu.rpc.RpcProtocol;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

public class InterfaceProxy implements InvocationHandler {

    //两种调用方式 返回值为void则只发送，不等待接受；反之则要等待接受
    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        StringBuilder sendMsg = new StringBuilder();
        String mName = RpcProtocol.getConsumerMethodRpcName(method);
        RpcMsgCallBack msgCallBack = RpcProtocol.encode(method,mName,objects,sendMsg);
        RpcRequest.sendRpcRequestMsg(mName,sendMsg, MsgType.callReq);
        switch (RpcRequest.getMethodCallType(mName)){
            case OneWay:
                return null;
            case Sync:
                return RpcProtocol.getParamObj(method.getReturnType(),String.valueOf(msgCallBack.getResult()));
            case Async:
                msgCallBack.setAsyncClass(method);
                return msgCallBack;
        }
        if (method.getReturnType() == void.class){
            //不用返回调用结果
            return null;
        }
        return RpcProtocol.getParamObj(method.getReturnType(),String.valueOf(msgCallBack.getResult()));
    }
    public static <T> T newInstance(Class<T> innerInterface) {
        ClassLoader classLoader = innerInterface.getClassLoader();
        Class[] interfaces = new Class[] { innerInterface };
        InterfaceProxy proxy = new InterfaceProxy();
        return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
    }


}
